import {observable, action} from "mobx";
import {Bubble, Tools, Modal, Toast} from "weaver-mobile";
import {Form, ListViewPage, RouteLayout} from "weaver-mobile-page";
import {Base64} from "js-base64";
import ReplyEditorStore from "../reply/replyEditorStore";
import * as API from "../../api";

const getLabel = Tools.getLabel;
export default class ProjectsStore {
    @observable isLoading = true;
    @observable Toasting = false;
    @observable hasRight = true;
    @observable docSearchVal = "";
    @observable tabIndex = 0;
    @observable currentPage = 1;
    @observable rightMenus = {};
    @observable prjid;
    @observable stageid;
    @observable viewtype = "view";
    @observable add_edit_Stage_State = "add";
    @observable exchange;


    @observable id;
    @observable source;
    @observable replyTypes = [];
    @observable form = new Form.Store();
    @observable PrjStateList = new ListViewPage.Store({route: "/ProjectDetails", id: "1"});
    @observable PrjExchange = new ListViewPage.Store({route: "/ProjectDetails", id: "2"});
    @observable PrjTaskList = new ListViewPage.Store({route: "/ProjectDetails", id: "3"});
    @observable RelativeDocList = new ListViewPage.Store({route: "/ProjectDetails", id: "4"});

    @observable stageForm = new Form.Store();
    @observable layout = new RouteLayout.Store({route: `/ProjectDetails/1/${this.prjid}/layout`});

    @observable comment = new ReplyEditorStore();

    @observable echartsOptions = {
        actualdate: [],
        begindate: [],
        finish: [],
        mindate: "",
        names: [],
        realmanday: [],
        workday: []
    };

    @action
    init = (index, prjid, viewtype) => {
        this.tabIndex = Number(index);
        this.prjid = prjid;
        this.layout = new RouteLayout.Store({route: `/ProjectDetails/1/${prjid}/layout`});
        this.viewtype = viewtype;
        this.rightMenus = {};

        if (this.tabIndex === 0) {
            this.getForm();
        } else if (this.tabIndex === 1) {
            this.getPrjStageList();
        } else if (this.tabIndex === 2) {
            this.getPrjTaskList();
        } else if (this.tabIndex === 3) {
            this.comment = new ReplyEditorStore({
                getComment: this.getReplyDatas,
                source: {prjid: this.prjid},
            });
            this.currentPage = 1;
            this.comment.commentStore.getDatas();
        } else if (this.tabIndex === 4) {
            this.getRelativeDocList();
        } else if (this.tabIndex === 5) {
            this.getPrjGantt()
        }
    };
    @action
    onTabChange = (index, history) => {
        this.tabIndex = Number(index);
        history.replace("/ProjectDetails/" + index + "/" + this.prjid)
    };
    @action
    setPage = (p) => {
        this.currentPage = p;
    }

    @action
    getForm = () => {
        this.isLoading = true;
        this.hasRight = true;
        const params = {
            prjid: this.prjid,
            viewtype: "view"
        }
        this.form = new Form.Store();
        API.getProjectForm(params).then(action(res => {
            this.isLoading = false;
            if (res["isright"] && res["isright"] === true) {
                this.rightMenus = res.rightMenus || {};
                this.form.initForm(res.fieldinfo, "/ProjectDetails/prj");
            } else {
                this.hasRight = false;
            }
        }))
    };

    @action
    getPrjStageList = () => {
        this.hasRight = true;
        const params = {
            prjid: this.prjid
        }
        this.PrjStateList.clearData();
        API.getPrjStageList(params).then(action(res => {
            if (res["isright"] && res["isright"] === true) {
                this.rightMenus = res.rightMenus || {};
                this.PrjStateList.getData({dataKey: res.datas});
            } else {
                this.hasRight = false;
            }
        }))
    }
    @action
    getPrjTaskList = () => {
        this.hasRight = true;
        const params = {
            prjid: this.prjid
        }
        this.PrjTaskList.clearData();
        API.getPrjTaskList(params).then(action(res => {
            if (res["isright"] && res["isright"] === true) {
                this.rightMenus = res.rightMenus || {};
                this.PrjTaskList.getData({dataKey: res.datas});
            } else {
                this.hasRight = false;
            }
        }))
    }
    @action
    getReplyDatas = () => {
        this.hasRight = true;
        const params = {
            sortid: this.prjid,
            pageindex: this.currentPage++
        }
        return API.getPrjExchange(params).then(action(res => {
            if (res["isright"] && res["isright"] === true) {
                this.hasRight = true;
                this.rightMenus = res.rightMenus || {};
                this.replyTypes = [].concat(res.replyTypes);
            } else {
                this.hasRight = false;
            }

            const result = res;
            result.replyList.forEach(v => {
                let imgArr = [];
                let content = Base64.decode(v.content);                                 //解码
                let src = content.match(/\bsrc\b\s*=\s*[\'\"]?([^\'\"\s]*)[\'\"]?/ig);  //查找img
                content = content.replace(/<img\b.*?(?:\>|\/>)/gi, "");                 //去除remark 中上传的img（带有fileid字段）
                // content=content.replace(/(<\/?a.*?>)/g, '');                            //去除a标签
                const aTags = content.match(/<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi) //搜索所有a标签
                if (aTags) {
                    aTags.forEach(v => {
                        const href = v.match(/<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)<\/a>/)    //查找href和value，并替换href
                        if (href) {
                            content = content.replace(href[1], "javascript:void(0)");
                        }
                    })
                }
                v.content = Base64.encode(content)                                      //编码
                if (src !== null) {
                    src.forEach(v => {
                        const fileid = v.match(/fileid=([a-zA-Z0-9]*)/i)                      //获取fileid
                        if (fileid) {
                            const temp = Array.from(fileid);
                            imgArr.push(temp[1]);                                       //拼接成数组
                        }
                    })
                }
                v.imgArr = imgArr;
            })
            return result
        }))
    }
    @action
    getRelativeDocList = () => {
        this.hasRight = true;
        const params = {
            prjid: this.prjid,
            name: this.docSearchVal
        };
        this.RelativeDocList.clearData();
        API.getPrjReferenceDoc(params).then(action(res => {
            if (res["isright"] && res["isright"] === true) {
                this.rightMenus = res.rightMenus || {};
                this.RelativeDocList.getData({dataKey: res.datas});
            } else {
                this.hasRight = false;
            }
        }))
    }
    @action
    getPrjGantt = () => {
        this.isLoading = true;
        const params = {
            prjid: this.prjid
        };
        API.getPrjGantt(params).then(action(res => {
            this.isLoading = false;
            this.echartsOptions = res;
        }))
    }

    @action
    changeSearchValue = (val) => {
        if (this.tabIndex === 4) {
            this.docSearchVal = val;
        }
    };


    @action
    changeStateTo = (state) => {
        const params = {
            prjid: this.prjid,
            method: state
        };
        let msglabel = "";
        if("normal"==state){
            msglabel = getLabel("500831", "项目状态已修改为")+"["+this.rightMenus.menulabels.btn_onNormal+"]";
        }else if("delay"==state){
            msglabel = getLabel("500831", "项目状态已修改为")+"["+this.rightMenus.menulabels.btn_onOver+"]";
        }else if("complete"==state){
            msglabel = getLabel("500831", "项目状态已修改为")+"["+this.rightMenus.menulabels.btn_onFinish+"]";
        }else if("freeze"==state){
            msglabel = getLabel("500831", "项目状态已修改为")+"["+this.rightMenus.menulabels.btn_onFrozen+"]";
        }else if("submitplan"==state){
            msglabel = getLabel("83923", "提交成功！");
        }else if("approveplan"==state){
            msglabel = getLabel("83923", "提交成功！");
        }
        API.doPrjPlanOperation(params).then(action(res => {
            if (res.success) {
                Bubble.success(msglabel, 1);
                this.init(this.tabIndex, this.prjid, this.viewtype);
            } else {
                Bubble.error(res.msg, 1);
            }
        }))
    }

    @action
    deleteCard = (history) => {
        const params = {
            method: "delete",
            prjid: this.prjid
        }

        Modal.alert(getLabel("15172", "系统提示"), getLabel("15097", "确定要删除吗？"), [
            {text: getLabel("31129", "取消")},
            {
                text: getLabel("826", "确定"), onPress: () => {
                    Toast.loading("Loading...", 10000);
                    this.Toasting = true;
                    API.doProjectOperation(params).then(action(res => {
                        Toast.hide();
                        this.Toasting = false;
                        if (res.success) {
                            Bubble.success(getLabel("83472", "删除成功！"), 1);
                            // this.init(this.tabIndex, this.prjid, this.viewtype);
                            history.go(-1)
                        } else {
                            Bubble.error(res.msg, 1);
                        }
                    }))
                }
            },
        ])
    }

    @action
    add_edit_Stage = (history, id) => {
        history.push(this.layout.path);
        let viewtype;
        if (id === undefined) {
            viewtype = "add";
        } else {
            viewtype = "edit";
        }
        this.add_edit_Stage_State = viewtype;
        this.stageid = id;
        const params = {
            viewtype: viewtype,
            stageid: id
        };
        API.getPrjStageForm(params).then(action(res => {
            this.stageForm = new Form.Store();
            this.stageForm.initForm(res.fieldinfo, "/ProjectDetails/prj");
        }))
    }

    @action
    saveStage = (history) => {
        if (this.stageForm.doValidate().pass) {
            Toast.loading("Loading...", 10000);
            this.Toasting = true;
            const formParams = this.stageForm.formParams;
            let params = {
                method: this.add_edit_Stage_State,
                prjid: this.prjid,
                name: formParams.name,
                description: formParams.description,
            };
            if (this.stageid !== undefined) {
                params = {...params, id: this.stageid}
            }
            API.doPrjStageOperation(params).then(action(res => {
                Toast.hide()
                this.Toasting = false;
                if (res.success) {
                    Bubble.success(res.msg, 1)
                    history.go(-1)
                    this.init(this.tabIndex, this.prjid, this, this.viewtype);
                } else {
                    Bubble.error(res.msg, 1)
                }
            }))
        }
    }

    @action
    deleteStage = (history, id) => {
        Toast.loading("Loading...", 10000);
        this.Toasting = true;
        const params = {
            method: "delete",
            prjid: this.prjid,
            id: id
        }
        API.doPrjStageOperation(params).then(action(res => {
            Toast.hide()
            this.Toasting = false;
            if (res.success) {
                Bubble.success(res.msg, 1)
                this.init(this.tabIndex, this.prjid, this, this.viewtype);
            } else {
                Bubble.error(res.msg, 1)
            }
        }))
    }
    @action
    linkToAccessory = (url) => {
        if (url) {
            try {
                window.em.openLink({
                    url: url, // 要打开链接的地址
                    openType: 2, // 打开方式 1:当前窗口 2:新窗口 3:系统默认浏览器
                    sysId: window.localStorage.emobile_ec_id    // 集成系统ID
                });
            } catch (e) {
            }
        }
    }

    @action
    triggerBreakDownWF = (params = {}) =>{
		const newParams = { prjid: this.prjid,...params}
		Tools.callApi({method:'POST',url:'/api/proj/pctask/triggerBreakDownWF',params:newParams}).then(action(data => {
			if(data.msg=='success'){
				this.getPrjTaskList();
				Bubble.success(getLabel('513071',"触发流程成功1！"),1);
			}else{
				Bubble.error(getLabel('513072',"触发流程失败1！"),1);
			}
		}));
	}

}
